import json

import requests

from utils.bokuEnum import bokukb, bokuzz, bokutype
from utils.tools import url_to_base64, parse_number, compare_labels, parse_label_value
from lxml import etree
import re


def getPublisherCodeByIsbn(isbn, session_id):
    cookies = {
        'PHPSESSID': session_id,
    }
    params = {
        'act': 'isbnTobb',
    }
    data = {
        'isbn': isbn,
    }
    response = requests.post(
        'https://gys2.bookuu.com/cloud/goods/v2/list.php',
        params=params,
        cookies=cookies,
        data=data,
    )
    response_json = json.loads(response.text)
    if 'bb' in response_json and 'cbsmc' in response_json and response_json['bb'] is not None and response_json[
        'bb'] != '' and response_json['cbsmc'] is not None and response_json['cbsmc'] != '':
        # {'status': 1, 'bb': '7213', 'cbsmc': '浙江人民出版社'}
        return {'code': 200, 'cbs': response_json['cbsmc'], 'bb': response_json['bb']}
    else:
        return {'code': 0, 'message': '上架失败', 'reason': response_json}

def upload_boku_img(session_id, zhutu_dcc_url, edit_id, spbs):
    response = requests.post(
        'http://gys2.bookuu.com/cloud/goods/v2/input.php',
        params={
            'act': 'upload_image',
        },
        cookies={
            'PHPSESSID': session_id,
        },
        headers={
            'Referer': f'https://gys2.bookuu.com/cloud/goods/v2/input.php?spbs={spbs}',
        },
        data={
            'image_data': url_to_base64(zhutu_dcc_url['webUrl']),
            'dir_name': 'cover',
            'id': edit_id,
            'spbs': spbs,
        },
        verify=False,
    )
    result_json = json.loads(response.text)
    # 主图地址
    return result_json['url']


def get_bk_detail(response):
    # 定义一个正则表达式来匹配你的变量
    pattern = re.compile(r"bk_detail = '(.*?)'", re.DOTALL | re.MULTILINE)
    # 搜索匹配的数据
    match = pattern.search(response.text)
    # 判断是否有匹配
    if match:
        # 提取匹配的数据
        bk_detail_data = match.group(1)
        return bk_detail_data
    else:
        return None


# 获取博库select的value
def get_select_value(et, name):
    selected_option = et.xpath(f'//*[@name="{name}"]/option[@selected="selected"]')
    selected_value = selected_option[0].get('value') if selected_option else ''
    return selected_value


# 博库第一步提交基础信息
def submitFirstStep(book_details_json, session_id):
    book_details_json = book_details_json['data']
    if not book_details_json['isbn']:
        return {'code': 0, 'message': '请传入isbn'}
    if not book_details_json['priceFixed']:
        return {'code': 0, 'message': '请传入定价'}
    if not book_details_json['bookName']:
        return {'code': 0, 'message': '请传入书名'}
    if not book_details_json['publishName']:
        return {'code': 0, 'message': '请传入出版社'}
    if not book_details_json['authorName']:
        return {'code': 0, 'message': '请传入作者'}
    # 第一次上架基础信息
    word_number = parse_number(book_details_json['fontNumber'])
    if word_number != '':
        word_number = str(int(word_number) / 1000)
    boku_cid = '1064'
    if compare_labels(book_details_json['bookInfoAppendObj']['subjectKeyword'], bokutype) is not None:
        boku_cid = compare_labels(book_details_json['bookInfoAppendObj']['subjectKeyword'], bokutype)
    elif compare_labels(book_details_json['bookInfoAppendObj']['ordinaryKeyword'], bokutype) is not None:
        boku_cid = compare_labels(book_details_json['bookInfoAppendObj']['ordinaryKeyword'], bokutype)
    elif compare_labels(book_details_json['bookInfoAppendObj']['worldBookCategory'], bokutype) is not None:
        boku_cid = compare_labels(book_details_json['bookInfoAppendObj']['worldBookCategory'], bokutype)
    elif compare_labels(book_details_json['bookInfoAppendObj']['marketingCategoryName'], bokutype) is not None:
        boku_cid = compare_labels(book_details_json['bookInfoAppendObj']['marketingCategoryName'], bokutype)
    search_result = getPublisherCodeByIsbn(book_details_json['isbn'], session_id)
    if search_result['code'] == 0:
        return search_result
    book_base = {
        'isbn': book_details_json['isbn'],  # ISBN -- 必填
        'dj': book_details_json['priceFixed'],  # 定价 -- 必填
        'bk_cid': boku_cid,  # 博库分类 -- 必填
        'spmc': book_details_json['bookName'],  # 书名 -- 必填
        'bb': search_result['bb'],  # 出版社ID 啊啊啊。完蛋了
        'cbs': search_result['cbs'],  # 出版社 -- 必填
        'zyz': book_details_json['authorName'],  # 作者 -- 必填
        'tm': book_details_json['isbn'],  # 条码 -- 必填
        'zdp': '0',  # 重点品 -- 必填
        'zdp_sy': book_details_json['printNumber'],  # 首印数 DCC对应这个的是印数
        'zdp_sf': '',  # 建议首采量
        'bc': book_details_json['versionNo'] or '',  # 版次
        'yc': book_details_json['printNo'] or '',  # 印次
        'cbsj': book_details_json['publishDate'] or '',  # 出版时间
        'yssj': book_details_json['publishDate'] or '',  # 印刷时间
        'kb': parse_label_value(bokukb, book_details_json['bookSize']) or '',  # 开本
        'zz': parse_label_value(bokuzz, book_details_json['binding']) or '',  # 装帧
        'ys': parse_number(book_details_json['pagesNumber']) or '',  # 页数
        'zs': word_number,  # 字数
        'cd': book_details_json['bookInfoAppendObj']['lengthBook'] or '',  # 长(厘米)
        'kd': book_details_json['bookInfoAppendObj']['widthBook'] or '',  # 宽(厘米)
        'hd': book_details_json['bookInfoAppendObj']['depthBook'] or '',  # 厚(厘米)
        'zl': book_details_json['bookInfoAppendObj']['weight'] or '',  # 重量
        'mbcs': book_details_json['packetNumber'],  # 每包册数
        'gysspid': '',  # 供应商商品ID
        'ghzk': '',  # 供货折扣  # 等用户输入
        'ztflh': book_details_json['bookInfoAppendObj']['classificationNumber'] or '',  # 中图分类号
    }
    # return { 'code': 0, 'book_base': book_base }
    first_submit = requests.post(
        'http://gys2.bookuu.com/cloud/goods/v2/list.php',
        params={
            'act': 'addnew',
            'op': 'save',
        },
        cookies={
            'PHPSESSID': session_id,
        },
        headers={},
        data=book_base,
        verify=False,
    )
    first_submit_json = json.loads(first_submit.text)
    print('first_submit_json:')
    print(first_submit_json)
    if (first_submit_json['status'] != 1 or first_submit_json['spbs'] == '' or first_submit_json['spbs'] is None
            or first_submit_json['edit_id'] == '' or first_submit_json['edit_id'] is None):
        return {'code': 0, 'message': '上架基础信息失败!', 'reason': first_submit_json}
    else:
        return {'code': 200, 'message': '上架基础信息成功!', 'reason': first_submit_json}


# 博库第二步请求提交二次修改信息
def submitSecondStep(book_details_json, session_id):
    book_details_json = book_details_json['data']
    price = book_details_json['priceFixed']
    isbn = book_details_json['isbn']
    # 如果定价或者isbn不存在
    if price is None or isbn is None:
        return {'code': 0, 'message': 'DCC数据异常，没有isbn或者定价'}
    print(price, isbn)
    list_response = requests.get(
        f'https://gys2.bookuu.com/cloud/goods/v2/list.php?jblx=0&page=1&limit=20&op=&isbn={isbn}&spbs=&title=&zdp=&jblx=',
        cookies={
            'PHPSESSID': session_id,
        },
        headers={
            'X-Requested-With': 'XMLHttpRequest',
        },
        verify=False,
    )
    # 解析为json格式
    response_json = json.loads(list_response.text)
    if response_json.get('message', '') != '':
        return {'code': 0, 'message': response_json['message']}
    print(response_json)
    if not response_json.get('data', None) or len(response_json['data']) == 0:
        return {'code': 0, 'message': '在博库未找到对应数据'}
    list_result = response_json['data']
    # 根据isbn和定价选择对应的数据
    list_matches = [x for x in list_result if x.get('isbn') == isbn[:13] and float(x.get('price')) == float(price)]
    if len(list_matches) == 0:
        return {'code': 0, 'message': '在博库未找到对应数据'}
    if len(list_matches) > 1:
        return {'code': 0, 'message': '在博库找到多个数据'}
    spbs = list_matches[0]['spbs']
    edit_id = list_matches[0]['editor_id']
    # 获取HTML页面准备解析
    page_response = requests.get(
        f'https://gys2.bookuu.com/cloud/goods/v2/input.php?spbs={spbs}',
        cookies={
            'PHPSESSID': session_id,
        },
        verify=False,
    )
    et = etree.HTML(page_response.text)
    isbn = et.xpath('//*[@id="isbn"]')[0].get('value')
    dj = et.xpath('//*[@id="dj"]')[0].get('value')
    cbs = et.xpath('//*[@name="cbs"]')[0].get('value')
    spmc = et.xpath('//*[@name="spmc"]')[0].get('value')
    zyz = et.xpath('//*[@name="zyz"]')[0].get('value')
    tm = et.xpath('//*[@name="tm"]')[0].get('value')
    cbsj = et.xpath('//*[@id="cbsj"]')[0].get('value')
    yssj = et.xpath('//*[@id="yssj"]')[0].get('value')
    bc = et.xpath('//*[@name="bc"]')[0].get('value')
    yc = et.xpath('//*[@name="yc"]')[0].get('value')
    zdp = get_select_value(et, 'zdp')
    zdp_sy = et.xpath('//*[@name="zdp_sy"]')[0].get('value')  # 首印数
    zdp_sf = et.xpath('//*[@name="zdp_sy"]')[0].get('value')  # 建议首采量
    yhsm = et.xpath('//*[@name="yhsm"]')[0].get('value')  # 优化书名
    # 注意哦，第一个中图分类号不管怎么写都不会被提交
    sftz = get_select_value(et, 'sftz')  # 是否套装
    ys = et.xpath('//*[@name="ys"]')[0].get('value') or parse_number(book_details_json['pagesNumber']) or ''  # 页数
    word_number = parse_number(book_details_json.get('fontNumber', ''))
    if word_number:
        word_number = str(int(word_number) / 1000)
    zs = et.xpath('//*[@name="zs"]')[0].get('value') or word_number or ''  # 字数
    kb = get_select_value(et, 'kb') or parse_label_value(bokukb, book_details_json['bookSize'])
    zz = get_select_value(et, 'zz') or parse_label_value(bokuzz, book_details_json['binding'])
    mbcs = book_details_json['packetNumber']  # 每包册数 暂时40吧
    cd = et.xpath('//*[@name="cd"]')[0].get('value') or book_details_json['bookInfoAppendObj']['lengthBook'] or ''  # 长
    kd = et.xpath('//*[@name="kd"]')[0].get('value') or book_details_json['bookInfoAppendObj']['widthBook'] or ''  # 宽
    hd = et.xpath('//*[@name="hd"]')[0].get('value') or book_details_json['bookInfoAppendObj']['depthBook'] or ''  # 厚
    zl = et.xpath('//*[@name="zl"]')[0].get('value') or book_details_json['bookInfoAppendObj']['weight'] or ''  # 重量
    gysspid = et.xpath('//*[@name="gysspid"]')[0].get('value') or ''  # 供应商商品ID
    ghzk = ''  # 供货折扣 暂时不填
    ztflh = et.xpath('//*[@name="ztflh"]')[0].get('value') or book_details_json['bookInfoAppendObj'][
        'classificationNumber'] or ''
    bk_cid = get_select_value(et, 'bk_cid')  # 博库分类
    sccgl = get_select_value(et, 'sccgl') or ''  # 首次采购量

    def upload_images_concurrently(session_id, items, edit_id, spbs):
        results = []
        for item in items:
            result = upload_boku_img(session_id, item, edit_id, spbs)
            results.append(result)
        return results

    # 准备上传图片
    book_info_file_obj_list = book_details_json['bookInfoFileObjList']
    if not book_info_file_obj_list or len(book_info_file_obj_list) == 0:
        return {'code': 0, 'message': '暂无图片信息'}

    # 上传主图
    zhutu_dcc_url = next((item for item in book_info_file_obj_list if item["fileType"] == "1"), None)
    if not zhutu_dcc_url:
        return {'code': 0, 'message': '请传入主图'}
    zhutu_url = upload_boku_img(session_id, zhutu_dcc_url, edit_id, spbs)
    # 实拍图
    shipai_dcc_url = [item for item in book_info_file_obj_list if item.get('fileType') == "19"][:3]
    shipai_url = upload_images_concurrently(session_id, shipai_dcc_url, edit_id, spbs)
    # 版权图
    banquan_dcc_url = next((item for item in book_info_file_obj_list if item["fileType"] == "4"), None)
    if not banquan_dcc_url:
        return {'code': 0, 'message': '请传入版权图'}
    banquan_url = upload_boku_img(session_id, banquan_dcc_url, edit_id, spbs)

    # 条码图
    barcode_dcc_url = next((item for item in book_info_file_obj_list if item["fileType"] == "6"), None)
    if not barcode_dcc_url:
        return {'code': 0, 'message': '请传入条码图'}
    barcode_url = upload_boku_img(session_id, barcode_dcc_url, edit_id, spbs)

    # 透明素材图
    tmsc_dcc_url = next((item for item in book_info_file_obj_list if item["fileType"] == "9"), None)
    if not tmsc_dcc_url:
        return {'code': 0, 'message': '请传入透明素材图'}
    tmsc_url = upload_boku_img(session_id, tmsc_dcc_url, edit_id, spbs)

    # 详情图
    detail_dcc_url = [item for item in book_info_file_obj_list if item.get('fileType') == "17"][:3]
    detail_url = upload_images_concurrently(session_id, detail_dcc_url, edit_id, spbs)

    book_all_json = {
        'edit_id': edit_id,  # 编辑ID 必填
        'spbs': spbs,  # 商品编号 必填
        'isbn': isbn,  # ISBN 必填
        'ori[isbn][v]': isbn,
        'ori[isbn][n]': 'ISBN',
        'dj': dj,  # 定价 必填
        'ori[dj][v]': dj,
        'ori[dj][n]': '定价',
        'cbs': cbs,  # 出版社 必填
        'ori[cbs][v]': cbs,
        'ori[cbs][n]': '出版社',
        'spmc': spmc,  # 书名 必填
        'zyz': zyz,  # 作者 必填
        'ori[zyz][v]': zyz,
        'ori[zyz][n]': '作者',
        "zdp": zdp or 0,  # 重点品 必填 默认非重点品
        'zdp_sy': zdp_sy,  # 首印数 非必填 --- DCC没这个字段 !!!
        'zdp_sf': zdp_sf,  # 建议首采量 --- 好像这个字段不用填 ^_^
        'yhsm': yhsm,  # 优化书名 --- 好像这个字段不用填 ^_^
        'tm': tm,  # 条码 非必填
        'sftz': sftz,  # 是否套装 非必填 --- 好像这个字段暂时也不用填 ^_^
        'ori[tm][v]': tm,
        'ori[tm][n]': '条码',
        'cbsj': cbsj,  # 出版时间 非必填
        'ori[cbsj][v]': cbsj,
        'ori[cbsj][n]': '出版时间',
        'yssj': yssj,  # 印刷时间 非必填
        'ori[yssj][v]': yssj,
        'ori[yssj][n]': '印刷时间',
        'bc': bc,  # 版次 非必填
        'ori[bc][v]': bc,
        'ori[bc][n]': '版次',
        'yc': yc,  # 印次 非必填
        'ori[yc][v]': yc,
        'ori[yc][n]': '印次',
        'ys': ys,  # 页数
        'zs': zs,  # 字数
        'kb': kb,  # 开本
        'zz': zz,  # 装帧
        'mbcs': mbcs,  # 每包册数 -- 必填
        'cd': cd,  # 长度(厘米)
        'kd': kd,  # 宽度(厘米)
        'hd': hd,  # 厚(厘米)
        'zl': zl,  # 重量(克)
        'gysspid': gysspid,  # 供应商商品ID
        'ghzk': ghzk,  # 供货折扣 暂时不填
        'ztflh': ztflh,  # 中图分类号
        'bk_cid': bk_cid,  # 博库分类
        'sccgl': sccgl,  # 首次采购量
        "file": "C:\\fakepath\\tutu.png",
        # 未知 C:\fakepath\+最后一张详情图的名字 -- 应该是没啥用
        "jcsz": book_details_json['bookInfoAdditionObj']['wonderfulClips'] or '',  # 精彩书摘
        "nrjs": book_details_json['bookInfoAdditionObj']['briefIntroduction'] or '',  # 内容介绍
        "ml": book_details_json['bookInfoAdditionObj']['tableOfContents'] or '',  # 目录
        "zzjj": book_details_json['bookInfoAdditionObj']['authorAbout'] or '',  # 作者简介
        "bjtj": book_details_json['bookInfoAdditionObj']['editRecommend'] or '',  # 编辑推荐
        "jcsp": "",  # 精彩书评
        "xy": book_details_json['bookInfoAdditionObj']['preface'] or '',  # 前言/序言
        "cpts": "",  # 产品特色
        "diff_field": "",  # 未知
        "bk_detail": get_bk_detail(page_response)
    }

    def format_data(obj, name, data):
        result = ""
        if len(data) > 0:
            for i in range(len(data)):
                key = f"{name}[{i}]"
                obj[key] = data[i]
                result += f"'{key}': '{data[i]}'"
                if i < len(data) - 1:
                    result += ", "

    # 商品主图 -- 必填 只能传一张 图片尺寸为800*800以上且大小不超过500KB
    format_data(book_all_json, 'cover', [zhutu_url])
    # 白底立体封 --非必填 只能传一张 必须白底，不能出现书籍以外的文字，图片尺寸为800*800以上且大小不超过500K
    format_data(book_all_json, 'rising', [zhutu_url])
    # 实拍图 --非必填 图片尺寸为800*800以上且大小不超过500K，最多添加3张，提交后可修改
    format_data(book_all_json, 'realshot', shipai_url)
    # 版权图 --非必填 只能传一张
    format_data(book_all_json, 'copyright', [banquan_url])
    # 条码图 --非必填 只能传一张
    format_data(book_all_json, 'barcode', [barcode_url])
    # 透明素材图 --非必填 只能传一张图片尺寸为800*800，且大小不超过1MB 图片格式为png
    format_data(book_all_json, 'lucency', [tmsc_url])
    # 详情图 --非必填 图片类型只能为png、jpg、jpeg,且大小不超过5MB
    format_data(book_all_json, 'detail', detail_url)
    final_response = requests.post(
        'http://gys2.bookuu.com/cloud/goods/v2/input.php',
        params={
            'act': 'save',
        },
        cookies={
            'PHPSESSID': session_id,
        },
        headers={
            'X-Requested-With': 'XMLHttpRequest',
        },
        data=book_all_json,
        verify=False,
    )
    final_response_json = json.loads(final_response.text)
    print(final_response_json)
    if final_response_json['status'] in ['1', 1]:
        return {'code': 200, 'message': '操作成功！', 'reason': final_response_json}
    else:
        return {'code': 0, 'message': '上架详细信息失败', 'reason': final_response_json}
